import React, {AnchorHTMLAttributes, ButtonHTMLAttributes, ReactNode} from 'react';
import classnames from 'classnames'

// 按钮大小
export type ButtonSize = 'lg' | 'sm'

/**
 * 按钮类型 'primary' | 'default' | 'danger' | 'link'
 */
export type ButtonType = 'primary' | 'default' | 'danger' | 'link'


export interface BaseButtonProps {
  /**
   * 样式
   */
  className?: string
  /**
   * 是否禁用
   */
  disabled?: boolean
  /**
   * 按钮大小
   */
  size?: ButtonSize
  /**
   * 按钮类型
   */
  btnType?: ButtonType
  /**
   * 外链(btnType==="link"才会生效)
   */
  href?: string
  /**
   * react元素
   */
  children: ReactNode
}


export type NativeButtonProps = BaseButtonProps & ButtonHTMLAttributes<HTMLElement>
export type AnchorButtonProps = BaseButtonProps & AnchorHTMLAttributes<HTMLElement>
// Partial 变成可选参数
export type ButtonProps = Partial<NativeButtonProps & AnchorButtonProps>

/**
 * 按钮组件
 */
export const Button: React.FC<ButtonProps> = (props) => {

  const {
    className, disabled, size, btnType, href, children,
    ...restProps
  } = props

  // 拼接字符串，false代表class不加入进来
  const classes = classnames('btn', className, {
    [`btn-${size}`]: size,
    [`btn-${btnType}`]: btnType,
    [`disabled`]: (btnType === "link") && disabled,
  })
  // 如果是连接，返回a标签，否则返回button标签
  if (btnType === "link" && href) {
    return <a href={href} className={classes} {...restProps} >{children}</a>
  } else {
    return <button
      className={classes} disabled={disabled}
      {...restProps}
    >{children}</button>
  }

}

Button.defaultProps = {
  btnType: "default",
  disabled: false
}

export default Button
